﻿
package extremefx {
	/**
	 * @author Marcelo Volmaro
	 */
	public class DateRange implements IEquatable{
		private var _start:DateTime;
		private var _end:DateTime;
		
		/**
		 * Initializes a new instance of the DateRange class
		 * @param pStartDate The starting date
		 * @param pEndDate The ending date
		 */
		public function DateRange(pStartDate:DateTime, pEndDate:DateTime) {
			if (pStartDate.ticks > pEndDate.ticks) {
				_start = pEndDate;
				_end = pStartDate;
			} else {
				_start = pStartDate;
				_end = pEndDate;
			}
		}
		
		/**
		 * Gets the <code>TimeSpan<code> defined between <code>endDate</code> and <code>startDate</code>
		 */
		public function get timeSpan():TimeSpan {
			return _end.subtractDateTime(_start);
		}
		
		/**
		 * Gets the start date of the <code>DateRange</code>
		 */
		public function get startDate():DateTime {
			return _start;
		}
		
		/**
		 * Gets the end date of the <code>DateRange</code>
		 */
		public function get endDate():DateTime {
			return _end;
		}
		
		/**
		 * Gets the intersection between this range and <code>pRange</code>
		 * @param pRange The <code>DateRange</code> to intersect with
		 * @return A <code>DateRange</code> containing the intersection if found, null if no intersection.
		 */
		public function getIntersection(pRange:DateRange):DateRange {
			var startDate1:Number = _start.ticks || 0;
			var startDate2:Number = pRange.startDate.ticks || 0;
			
			var endDate1:Number = _end.ticks || Number.MAX_VALUE;
			var endDate2:Number = pRange.endDate.ticks || Number.MAX_VALUE;
			
			var left:Number = Math.max(startDate1, startDate2);
			var right:Number = Math.min(endDate1, endDate2);
	
			if (right < left) return null;
			return new DateRange(new DateTime(left), new DateTime(right));
		}
		
		/**
		 * Checks if this range intersects with <code>pRange</code>
		 * @return A <code>Boolean</code> that indicates if the two ranges intersects or not.
		 */
		public function intersects(pRange:DateRange):Boolean {
			return getIntersection(pRange) != null;
		}
		
		public function equals(pObj:*):Boolean {
			if (pObj is DateRange){
				var other:DateRange = pObj as DateRange;
				return (other.startDate.equals(startDate) && other.endDate.equals(endDate));
			}
			return false;
		}
	}
}
